package com.ff.miaosha.controller;

import com.ff.miaosha.access.AccessLimit;
import com.ff.miaosha.domain.MiaoshaOrder;
import com.ff.miaosha.domain.MiaoshaUser;
import com.ff.miaosha.domain.OrderInfo;
import com.ff.miaosha.rabbitmq.MQSender;
import com.ff.miaosha.rabbitmq.MiaoshaMessage;
import com.ff.miaosha.redis.GoodsKey;
import com.ff.miaosha.redis.RedisService;
import com.ff.miaosha.result.CodeMsg;
import com.ff.miaosha.result.Result;
import com.ff.miaosha.service.GoodsService;
import com.ff.miaosha.service.MiaoshaService;
import com.ff.miaosha.service.MiaoshaUserService;
import com.ff.miaosha.service.OrderService;
import com.ff.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("miaosha")
public class MiaoshaController implements InitializingBean{

    @Autowired
    MiaoshaService miaoshaService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisService redisService;

    @Autowired
    MQSender mqSender;

    private HashMap<Integer,Boolean> localOverMap=new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        //获取所有秒杀商品
        List<GoodsVo> goodsList=goodsService.listGoodsVo();
        if (goodsList==null){
            return;
        }
        for (GoodsVo goods:goodsList){
            redisService.set(GoodsKey.getMiaoshaGoodsStock,""+goods.getId(),goods.getStockCount());
            localOverMap.put(goods.getId(),false);
        }
    }

    @AccessLimit(seconds = 5,maxCount = 5,needLogin = true)
    @RequestMapping(value = "/path",method = RequestMethod.GET)
    @ResponseBody
    public Result<String> getMiaoshaPath(HttpServletRequest request,MiaoshaUser user,
                                         @RequestParam("goodsId")long goodsId,
                                         @RequestParam(value = "verifyCode" ,defaultValue="0")int verifyCode){

        boolean check=miaoshaService.checkVerifyCode(user,goodsId,verifyCode);
        if (!check){
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        }
        String path=miaoshaService.createMiaoshaPath(user,goodsId);
        return Result.success(path);
    }


    @RequestMapping("/{path}/do_miaosha")
    @ResponseBody
    public Result<Integer> list2( MiaoshaUser user,
                       @RequestParam("goodsId")int goodsId,@PathVariable("path")String path){
        if (user==null){
            return Result.error(CodeMsg.SESSION_ERROR);
        }
        boolean check=miaoshaService.checkPath(user,goodsId,path);
        if (!check){
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        }
        //内存标记，减少redis访问
        if (localOverMap.get(goodsId)){
            return Result.error(CodeMsg.MIAO_SHA_OVER);
        }
        //预减库存
        long stock=redisService.decr(GoodsKey.getMiaoshaGoodsStock,""+goodsId);
        if (stock<0){
            localOverMap.put(goodsId,true);
            return Result.error(CodeMsg.MIAO_SHA_OVER);
        }

        //判断是否已经秒杀到了
        MiaoshaOrder order=orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(),goodsId);
        if (order!=null){
            return Result.error(CodeMsg.REPETE_MIAOSHA);
        }
       //入队
        MiaoshaMessage mm=new MiaoshaMessage();
        mm.setUser(user);
        mm.setGoodsId(goodsId);
        mqSender.sendMiaoshaMessage(mm);
        return Result.success(0);
    }

    /*@RequestMapping("do_miaosha2")
    public String list(Model model, MiaoshaUser user,
                       @RequestParam("goodsId")long goodsId){
        model.addAttribute("user",user);
        if (user==null){
            return "login";
        }
        //判断库存
        GoodsVo goodsVo=goodsService.getGoodsVoByGoodsId(goodsId);
        int stock=goodsVo.getGoodsStock();
        if (stock<=0){
            model.addAttribute("errmsg", CodeMsg.MIAO_SHA_OVER.getMsg());
            return "miaosha_fail";
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order=orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(),goodsId);
        if (order!=null){
            model.addAttribute("errmsg",CodeMsg.REPETE_MIAOSHA.getMsg());
            return "miaosha_fail";
        }
        //减库存 下订单 写入秒杀订单
        OrderInfo orderInfo=miaoshaService.miaosha(user,goodsVo);
        model.addAttribute("orderInfo",orderInfo);
        model.addAttribute("goods",goodsVo);
        return "order_detail";
    }*/



    /**
     * orderId：成功
     * -1：秒杀失败
     * 0： 排队中
     * */
    @AccessLimit(seconds=5, maxCount=5, needLogin=true)
    @GetMapping("/result")
    @ResponseBody
    public Result<Long> miaoshaResult(MiaoshaUser user,@RequestParam("goodsId")long goodsId){
        if (user==null){
            return Result.error(CodeMsg.SESSION_ERROR);
        }
        long result=miaoshaService.getMiaoshaResult(user.getId(),goodsId);
        return Result.success(result);
    }

    @RequestMapping(value = "verifyCode",method = RequestMethod.GET)
    @ResponseBody
    public Result<String> getMiaoshaVerifyCode(HttpServletResponse response,MiaoshaUser user,
                                               @RequestParam("goodsId") long goodsId){
        if (user==null){
            return Result.error(CodeMsg.SESSION_ERROR);
        }
        try {
            BufferedImage image=miaoshaService.createVerifyCode(user,goodsId);
            OutputStream out=response.getOutputStream();
            ImageIO.write(image,"JPEG",out);
            out.flush();
            out.close();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(CodeMsg.MIAO_SHA_FAIL);
        }
    }

}
